<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.menu_name"
            placeholder="搜索商品名称"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-input
            oninput="this.value=this.value.replace(/[^\d]/g, '');"
            v-model="formSearch.priceMin"
            placeholder="开始价格"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item> ~ </el-form-item>

        <el-form-item>
          <el-input
            oninput="this.value=this.value.replace(/[^\d]/g, '');"
            v-model="formSearch.priceMax"
            placeholder="结束价格"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-cascader
            v-model="formSearch.merchant_id"
            :props="casProps"
            :options="casOptions"
            placeholder="请选择分类"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            v-if="permission.MenuSkuList"
            type="primary"
            @click="goMenuSku"
            >分类管理</el-button
          >
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-show="permission.add"
            >商品添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          :show-overflow-tooltip="tooltip"
          label="商品名"
        ></el-table-column>
        <el-table-column
          prop="goodsType"
          :show-overflow-tooltip="tooltip"
          label="商品分类"
        ></el-table-column>

        <el-table-column prop="mainPicture" label="图片" align="center">
          <template slot-scope="scope">
            <div class="img" style="cursor: pointer">
              <viewer>
                <img
                  :src="scope.row.mainPicture"
                  alt
                  :onerror="errImg"
                  title="查看高清图片"
                  style="width: 40px; height: 40px; border-radius: 50%"
                />
              </viewer>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sellingPrice" label="价格"></el-table-column>
        <el-table-column prop="specifications" label="规格"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="isSale" label="是否上架" align="center">
          <template slot-scope="scope">
            <el-tag type="success" size="small" v-if="scope.row.isSale == 1"
              >是</el-tag
            >
            <el-tag type="danger" size="small" v-else>否</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="320" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.isSale == 1"
              size="mini"
              @click="goMenuTastes(scope.row)"
              v-show="permission.MenuTastes"
              >下架</el-button
            >
            <el-button
              type="primary"
              v-else
              size="mini"
              @click="goMenuTastes(scope.row)"
              v-show="permission.MenuTastes"
              >上架</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 商品添加和商品编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加商品' : '修改商品'"
        :visible.sync="visible"
        width="50%"
        @close="onCancel('ruleForm')"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="80px"
          class="form-drawer__main"
        >
          <el-form-item label="产品分类" prop="cate_id">
            <el-cascader
              class="formInput"
              v-model="ruleForm.cate_id"
              :props="casProps"
              :options="casOptions"
              @change="casHandleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="产品标题"
            prop="menu_name"
            style="margin-bottom: 30px"
          >
            <el-input
              class="formInput"
              clearable
              maxlength="30"
              v-model="ruleForm.menu_name"
              placeholder="请输入产品标题"
            ></el-input>
          </el-form-item>
          <el-form-item label="产品标语" style="margin-bottom: 30px">
            <el-input
              type="textarea"
              placeholder="请输入产品标语"
              v-model="ruleForm.menu_content"
              :rows="5"
              maxlength="300"
              show-word-limit
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品主图"
            prop="menu_image"
            style="margin-bottom: 30px"
          >
            <UploadImage
              @getImgSrc="getImgSrc"
              :imageUrl.sync="ruleForm.menu_image"
              ref="image"
            />
          </el-form-item>
          <el-form-item
            label="详情图"
            prop="detail_images"
            style="margin-bottom: 30px"
          >
            <UploadImg
              @getImgSrc="getImgSrc3"
              :list.sync="ruleForm.detail_images"
              :options="options"
              ref="img"
            />
          </el-form-item>

          <el-form-item
            label="产品图文"
            prop="rotation_images"
            style="margin-bottom: 30px"
          >
            <Editor
              @onEditorChange="onEditorChange"
              :content="ruleForm.rotation_images"
              ref="editor"
            />
          </el-form-item>
          <el-form-item
            label="售卖价格"
            prop="menu_price"
            style="margin-bottom: 30px"
          >
            <el-input
              class="formInput"
              @mousewheel.native.prevent
              clearable
              type="number"
              v-model.number="ruleForm.menu_price"
              placeholder="请输入售卖价格"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>

          <el-form-item
            label="成本价格"
            prop="costPrice"
            style="margin-bottom: 30px"
          >
            <el-input
              class="formInput"
              @mousewheel.native.prevent
              clearable
              type="number"
              v-model.number="ruleForm.costPrice"
              placeholder="请输入成本价格"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>
          <el-form-item label="原价"  style="margin-bottom: 30px">
            <el-input
              class="formInput"
              @mousewheel.native.prevent
              clearable
              type="number"
              v-model.number="ruleForm.price"
              placeholder="请输入原价"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>
          <el-form-item
            label="是否上架"
            prop="is_show"
            style="margin-bottom: 30px"
          >
            <el-radio v-model="ruleForm.is_show" :label="1">上架</el-radio>
            <el-radio v-model="ruleForm.is_show" :label="2">下架</el-radio>
          </el-form-item>
          <el-form-item
            label="线上库存"
            prop="inventory"
            style="margin-bottom: 30px"
          >
            <el-input
              placeholder="请输入库存"
              class="formInput"
              v-model="ruleForm.inventory"
              oninput="this.value=this.value.replace(/[^\d]/g,'')"
            >
              <span slot="append">份</span>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  goodsList,
  goodsDel,
  goodsAdd,
  goodsEdit,
  goodsDetail,
  allType,
  typeList,
  MAIN,
  saleUpdate,
} from "../../utils/api";
import { validatPrices } from "../../utils/common";

import UploadImage from "../../components/UploadImage";
import UploadImg from "../../components/UploadImg";
import Editor from "../../components/Editor";
export default {
  name: "Taste",
  props: ["height"],
  components: {
    UploadImg,
    UploadImage,
    Editor,
  },
  data() {
    return {
      options: {
        type: "picture-card",
        limit: 5,
      }, //上传图片配置项
      tableData: [
        {
          id: 1,
        },
      ],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      permission: {
        add: false,
        edit: false,
        del: false,
        MenuTastes: false,
        MenuSkuList: false,
      }, //权限
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      formSearch: {
        merchant_id: "",
        menu_name: "",
        priceMin: "",
        priceMax: "",
        goodsId: "",
      }, //搜索
      userinfo: {},
      casOptions: [],
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        menu_name: "",
        menu_price: "",
        menu_image: "",
        is_show: 1,
        inventory: "",
        cate_id: "",
        menu_content: "",
        rotation_images: "", //轮播图片列表 商品
        detail_images: [], //详情图片列表 商品
        price: "",
        costPrice: "",
      }, //添加和修改的表单
      rules: {
        menu_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        menu_price: [
          { required: true, message: "请输入金额", trigger: "change" },
          {
            min: 1,
            max: 99999999,
            validator: validatPrices,
            trigger: "change",
          },
        ],
        price: [
          { required: true, message: "请输入金额", trigger: "change" },
          {
            min: 1,
            max: 99999999,
            validator: validatPrices,
            trigger: "change",
          },
        ],
        costPrice: [
          { required: true, message: "请输入金额", trigger: "change" },
          {
            min: 1,
            max: 99999999,
            validator: validatPrices,
            trigger: "change",
          },
        ],
        // costPrice
        menu_image: [
          { required: true, message: "请选择商品主图", trigger: "change" },
        ],

        inventory: [
          { required: true, message: "请输入商品库存", trigger: "blur" },
        ],
        cate_id: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],

        detail_images: [
          { required: true, message: "请选择详情图,", trigger: "change" },
        ],
      },
      merchant: {}, //商家列表
      cate: {}, //商品分类列表
    };
  },

  mounted() {
    this.getResource();

    this.cateSelects(); //商品分类列表
    if (this.$route.query.goodsId) {
      this.formSearch.goodsId = this.$route.query.goodsId;
      this.getData();
    }
  },
  methods: {
    //富文本框
    onEditorChange(e) {
      this.ruleForm.rotation_images = e;
    },
    casHandleChange() {},
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增商品 22
      // 修改商品 23
      // 删除商品 24
      // 分类管理 25
      // 下架 32
      if (arr.indexOf("22") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("23") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("24") > -1) {
        this.permission.del = true;
      }

      if (arr.indexOf("25") > -1) {
        this.permission.MenuSkuList = true;
      }
      if (arr.indexOf("32") > -1) {
        this.permission.MenuTastes = true;
      }

      this.getData();
      // this.merchantSelects(); //商家下拉列表
    },
    //清除输入框负数
    clearMinus(e, type) {
      let boolean = new RegExp("^[0-9][0-9.]*$").test(e.target.value);
      if (!boolean) {
        e.target.value = "";
        if (type === "menu_price") this.ruleForm.menu_price = "";
        if (type === "menu_money") this.ruleForm.menu_money = "";
      }
    },
    //   商家下拉列表
    merchantSelects() {
      this.postRequest(allType, {}, MAIN).then((res) => {
        if (res.code == 200) {
          this.merchant = res.data;
        }
      });
    },

    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    // 商品主图
    getImgSrc(e) {
      this.ruleForm.menu_image = e;
    },
    // 轮播图
    getImgSrc2(e) {
      this.ruleForm.rotation_images = e;
    },
    // 详情图
    getImgSrc3(e) {
      this.ruleForm.detail_images = e;
      // console.log(e);
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        userId: this.userinfo.id,
        name: this.formSearch.menu_name,
        priceMin: this.formSearch.priceMin,
        priceMax: this.formSearch.priceMax,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        goodsId: this.formSearch.goodsId,
        goodsTypeTwo: this.formSearch.merchant_id[1],
      };
      this.postRequest(goodsList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      console.log(this.ruleForm.detail_images);
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      // this.getMenuImages(row.id);
      // this.cateSelects(row.merchant_id); //商品分类列表
      this.currentRow = row;
      this.visible = true;
      this.postRequest(goodsDetail, { id: row.id }, MAIN).then((res) => {
        if (res.code == 200) {
          this.ruleForm = {
            menu_name: res.data.name,
            menu_price: res.data.sellingPrice,
            menu_image: res.data.mainPicture,
            detail_images: res.data.pictures,
            rotation_images: res.data.details,
            is_show: res.data.isSale,
            inventory: res.data.stock,
            cate_id: [row.goodsTypeOne, row.goodsTypeTwo],
            menu_content: res.data.slogan,
            costPrice: res.data.costPrice,
            price: res.data.price,
          };
          console.log(res.data);
        }
      });
    },
    // 获取当前商品的图片
    getMenuImages(id) {
      let parm = {
        menu_id: id,
      };
      this.postRequest(getMenuImages, parm, MAIN).then((res) => {
        if (res.code == 200) {
          this.ruleForm.detail_images = res.data.detail_images;
          this.ruleForm.rotation_images = res.data.rotation_images;
        }
      });
    },
    goMenuSku(row) {
      this.$router.push({
        path: "/MenuSkuList",
      });
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(goodsDel, parm, MAIN).then((res) => {
          if (res.code == 200) {
            this.$notify({
              title: "删除成功",
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      }).catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.addMenu();
          } else if (this.type == "edit") {
            this.editMenu();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    addMenu() {
      let params = {
        userId: this.userinfo.id,
        goodsTypeOne: this.ruleForm.cate_id[0],
        goodsTypeTwo: this.ruleForm.cate_id[1],
        name: this.ruleForm.menu_name,
        sellingPrice: this.ruleForm.menu_price,
        mainPicture: this.ruleForm.menu_image,
        isSale: this.ruleForm.is_show,
        stock: this.ruleForm.inventory,
        slogan: this.ruleForm.menu_content,
        details: this.ruleForm.rotation_images,
        pictures: this.ruleForm.detail_images.join(","),
        costPrice: this.ruleForm.costPrice,
        price: this.ruleForm.price,
      };

      this.postRequest(goodsAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    editMenu() {
      let params = {
        id: this.currentRow.id,
        userId: this.userinfo.id,
        goodsTypeOne: this.ruleForm.cate_id[0],
        goodsTypeTwo: this.ruleForm.cate_id[1],
        name: this.ruleForm.menu_name,
        sellingPrice: this.ruleForm.menu_price,
        mainPicture: this.ruleForm.menu_image,
        isSale: this.ruleForm.is_show,
        stock: this.ruleForm.inventory,
        slogan: this.ruleForm.menu_content,
        details: this.ruleForm.rotation_images,
        pictures: this.ruleForm.detail_images.join(","),
        costPrice: this.ruleForm.costPrice,
        price: this.ruleForm.price,
      };

      this.postRequest(goodsEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 关闭弹框
    onCancel(formName) {
      this.ruleForm.rotation_images = [];
      this.ruleForm.detail_images = [];
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      if (this.$refs.img) this.$refs.img.clear();
      if (this.$refs.image) this.$refs.image.clear();

      if (this.$refs.editor) this.$refs.editor.clear();
      this.confirmLoading = false;
      this.ruleForm = {
        menu_name: "",
        menu_price: "",
        menu_image: "",
        is_show: 1,
        inventory: "",
        cate_id: "",
        menu_content: "",
        rotation_images: "", //轮播图片列表 商品
        detail_images: [], //详情图片列表 商品
        costPrice: "",
        price: "",
      };
    },
    // 跳转到商品的规格
    goMenuSku(row) {
      this.$router.push({
        path: "/MenuSkuList",
        query: { menu_id: row.id, merchant_id: row.merchant_id },
      });
    },
    // 下架
    goMenuTastes(row) {
      let parm = {
        id: row.id,
        isSale: row.isSale == 1 ? 2 : 1,
      };
      this.$confirm("确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(saleUpdate, parm, MAIN).then((res) => {
          if (res.code == 200) {
            this.$notify({
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      });
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
.formInput {
  width: 300px;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}

/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 121px;
  height: 121px;
}
/deep/ .el-upload--picture-card {
  width: 121px;
  height: 121px;
  line-height: 130px;
}
</style>
